<template>
  <div class="mes-config-page">
    <h2>生产计划协同</h2>
    <div class="config-section">
      <label>
        <input type="checkbox" v-model="syncEnabled" @change="saveConfig" />
        启用维护计划同步
      </label>
    </div>

    <div class="order-section">
      <h3>工单生成</h3>
      <el-form :inline="true" :model="newOrder" class="order-form">
        <el-form-item label="工单名称">
          <el-input v-model="newOrder.name" placeholder="如：维护计划A"></el-input>
        </el-form-item>
        <el-form-item label="预计耗时(小时)">
          <el-input-number v-model="newOrder.duration" :min="1" :max="24"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createOrder">生成工单</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="plan-section">
      <h3>计划甘特图</h3>
      <div class="gantt-chart">
        <div
          v-for="task in tasks"
          :key="task.id"
          class="gantt-task"
          :class="{ affected: task.affected, recovered: task.recovered }"
        >
          <span class="task-name">{{ task.name }}</span>
          <span class="task-time">{{ task.start }} - {{ task.end }}</span>
          <span v-if="task.affected" class="affected-label">已调整</span>
          <span v-if="task.recovered" class="recovered-label">已恢复</span>
        </div>
      </div>
    </div>

    <div class="close-loop-section">
      <h3>工单闭环</h3>
      <el-button
        type="success"
        :disabled="!hasAffected"
        @click="recoverPlan"
      >更新生产计划</el-button>
    </div>
  </div>
</template>

<script>
import { Message } from 'element-ui';

const TASKS_KEY = 'mes_tasks';
const CONFIG_KEY = 'mes_config';
const ORDERS_KEY = 'mes_orders';

function getDefaultTasks() {
  // 模拟生产任务
  return [
    { id: 1, name: '订单A-工序1', start: '08:00', end: '10:00', device: '设备1', affected: false, recovered: false },
    { id: 2, name: '订单A-工序2', start: '10:00', end: '12:00', device: '设备1', affected: false, recovered: false },
    { id: 3, name: '订单A-工序3', start: '12:00', end: '16:00', device: '设备1', affected: false, recovered: false },
    { id: 4, name: '订单B-工序1', start: '16:00', end: '18:00', device: '设备2', affected: false, recovered: false },
    { id: 5, name: '订单C-工序1', start: '18:00', end: '20:00', device: '设备1', affected: false, recovered: false },
  ];
}

export default {
  name: 'MESConfigPage',
  data() {
    return {
      syncEnabled: false,
      newOrder: {
        name: '',
        duration: 4,
      },
      tasks: [],
      orders: [],
    };
  },
  computed: {
    hasAffected() {
      return this.tasks.some(t => t.affected && !t.recovered);
    },
  },
  created() {
    this.loadConfig();
    this.loadTasks();
    this.loadOrders();
  },
  methods: {
    // 配置持久化
    saveConfig() {
      localStorage.setItem(CONFIG_KEY, JSON.stringify({ syncEnabled: this.syncEnabled }));
    },
    loadConfig() {
      const conf = localStorage.getItem(CONFIG_KEY);
      if (conf) {
        this.syncEnabled = JSON.parse(conf).syncEnabled;
      }
    },
    // 工单持久化
    loadOrders() {
      const orders = localStorage.getItem(ORDERS_KEY);
      this.orders = orders ? JSON.parse(orders) : [];
    },
    saveOrders() {
      localStorage.setItem(ORDERS_KEY, JSON.stringify(this.orders));
    },
    // 任务持久化
    loadTasks() {
      const tasks = localStorage.getItem(TASKS_KEY);
      this.tasks = tasks ? JSON.parse(tasks) : getDefaultTasks();
    },
    saveTasks() {
      localStorage.setItem(TASKS_KEY, JSON.stringify(this.tasks));
    },
    // 工单生成
    createOrder() {
      if (!this.newOrder.name || !this.newOrder.duration) {
        Message.warning('请填写工单名称和预计耗时');
        return;
      }
      const order = {
        id: Date.now(),
        name: this.newOrder.name,
        duration: this.newOrder.duration,
        createdAt: new Date().toISOString(),
        synced: false,
      };
      this.orders.push(order);
      this.saveOrders();
      Message.success('工单已生成');
      if (this.syncEnabled) {
        this.syncToMES(order);
      }
      this.newOrder.name = '';
      this.newOrder.duration = 4;
    },
    // 维护计划同步
    syncToMES(order) {
      // 简化逻辑：找到第一个能被影响的任务（如订单A-工序3），并调整其时间
      let affected = false;
      const duration = order.duration;
      let found = false;
      let affectedIndex = -1;
      for (let i = 0; i < this.tasks.length; i++) {
        const t = this.tasks[i];
        // 只影响设备1的工序
        if (t.device === '设备1' && !t.affected && !found) {
          affected = true;
          found = true;
          affectedIndex = i;
          break;
        }
      }
      if (affected && affectedIndex !== -1) {
        // 调整该任务及其后的任务
        for (let i = affectedIndex; i < this.tasks.length; i++) {
          if (this.tasks[i].device === '设备1') {
            this.tasks[i].affected = true;
            // 简单模拟：将时间延后duration小时
            this.tasks[i].start = this.addHours(this.tasks[i].start, duration);
            this.tasks[i].end = this.addHours(this.tasks[i].end, duration);
          }
        }
        this.saveTasks();
        Message.info('维护计划已同步至MES，相关任务已调整');
      }
    },
    // 时间字符串加小时
    addHours(timeStr, hours) {
      const [h, m] = timeStr.split(':').map(Number);
      let newH = h + hours;
      if (newH >= 24) newH -= 24;
      return `${newH.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
    },
    // 工单闭环，恢复计划
    recoverPlan() {
      // 恢复所有受影响任务
      const duration = this.orders.length > 0 ? this.orders[this.orders.length - 1].duration : 4;
      for (let i = 0; i < this.tasks.length; i++) {
        if (this.tasks[i].affected && !this.tasks[i].recovered) {
          this.tasks[i].start = this.addHours(this.tasks[i].start, -duration);
          this.tasks[i].end = this.addHours(this.tasks[i].end, -duration);
          this.tasks[i].affected = false;
          this.tasks[i].recovered = true;
        }
      }
      this.saveTasks();
      Message.success('生产计划已恢复，资源已释放');
    },
  },
};
</script>

<style scoped>
.mes-config-page {
  max-width: 900px;
  margin: 30px auto;
  background: #fff;
  padding: 32px 40px;
  border-radius: 8px;
  box-shadow: 0 2px 8px #eee;
}
.config-section {
  margin-bottom: 24px;
}
.order-section {
  margin-bottom: 32px;
}
.order-form {
  margin-top: 12px;
}
.plan-section {
  margin-bottom: 32px;
}
.gantt-chart {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 16px;
  background: #fafbfc;
}
.gantt-task {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 12px;
  border-radius: 4px;
  background: #f5f7fa;
  font-size: 15px;
  position: relative;
}
.gantt-task.affected {
  background: #fffbe6;
  border-left: 4px solid #f7c948;
}
.gantt-task.recovered {
  background: #e6fffb;
  border-left: 4px solid #36cfc9;
}
.task-name {
  flex: 1;
  font-weight: 500;
}
.task-time {
  margin-left: 20px;
  color: #888;
}
.affected-label {
  margin-left: 16px;
  color: #faad14;
  font-weight: bold;
}
.recovered-label {
  margin-left: 16px;
  color: #13c2c2;
  font-weight: bold;
}
.close-loop-section {
  margin-top: 32px;
  text-align: right;
}
</style>
